import 'dart:async';

import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/model/order_list_manage_entity.dart';
import 'package:flutter_ncsjqz_getx/util/pay_auth_share_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

import 'order_view.dart';

class OrderLogic extends GetxController {
  List<String> tabs = ["全部","待付款","已完成","退款售后"];
  /// 分类 1 == "待付款", 2 == "已完成", 3 == "退款", 4 == "退款中"
  int currentIndex = 0;
  /// 订单数据
  List<OrderModel> orderData = [];
  // 0微信支付 1支付宝支付 / 接口所用：(1:微信支付 2:支付宝)
  int payType = 0;
  // 微信监听流
  StreamSubscription? streamSubscription;
  /// 切换分类
  setCurrentIndex(value) {
    currentIndex = value;
    getOrderListData();
    update();
  }
  /// 选择支付方式
  setPayType(int value){
    payType = value;
    update();
  }
  /// 获取订单列表数据
  getOrderListData() async{
    int type = 0;
    if(currentIndex == 1) type = 1;
    if(currentIndex == 2) type = 4;
    if(currentIndex == 3) type = 5;
    OrderListManageEntity orderListManageEntity = await DioService<OrderListManageEntity>().listOrderStatus(
      {'type': type}
    );
    orderData = [];
    if(orderListManageEntity.code == 0){
      orderListManageEntity.data!.forEach((element) {
        orderData.add(OrderModel(
          title: element.commodityName,
          img: element.masterPic,
          sku: element.skuName,
          count: element.orderCommodityCount,
          status: element.orderStatus,
          price: element.orderActualTotal,
          id: element.orderId.toString(),
          date: element.orderDvyTime,
          orderNo: element.orderNo,
        ));
      });
    }
    update();
  }

  canOrder(orderId) async{
    BaseEntity baseEntity = await DioService<BaseEntity>().userCancelOrder(
        {'orderId': orderId}
    );
    if(baseEntity.code == 0){
      toast("取消成功");
      Get.back();
      getOrderListData();
    }else{
      toast("取消失败");
    }
  }

  /// 对已提交并签名的订单进行支付
  orderPay(OrderModel orderModel) async{
    BaseEntity submitOrderEntity = await DioService<BaseEntity>().payOrder({
      "orderNos": [orderModel.orderNo],
      "payAmount": orderModel.price! * orderModel.count!,
      "payType": payType+1,
      "payTypeName": "${payType==1?'微信支付':'支付宝支付'}",
    });
    if(submitOrderEntity.code==0 && submitOrderEntity.data!=null){
      // 微信支付
      if(submitOrderEntity.data["payType"] == 1){
        PayUtil.wxPay(WxModel.toFormat(submitOrderEntity.data["data"]),);
      }else{
        // 支付宝支付
        PayUtil.alibabaPay(submitOrderEntity.data["data"],onCall: (v){
          if(v==0) {
            toast("支付成功");
            // Get.back();
          }
        });
      }
    }
  }

  /// 订阅微信操作
  wxEvent(){
    streamSubscription = weChatResponseEventHandler.listen((event) async {
      // 0	成功	展示成功页面
      // -1	错误	可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等。
      // -2	用户取消	无需处理。发生场景：用户不支付了，点击取消，返回APP。
      print('微信：${event.errCode}');
      if(event.errCode == 0){
        toast("支付成功");
        getOrderListData();
        Get.back();
      }else if(event.errCode == -2){
        toast("取消了支付，支付失败");
      }else{
        toast("支付失败,微信配置存在错误！请联系管理员");
      }
    });
  }
}
